package com.hjl.dao.impl;

import com.hjl.dao.UserDao;
import com.hjl.entity.User;
import com.hjl.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author ServivE
 * @version 0.1
 * @className UserDaoImpl
 * @description
 * @date 2024/7/24 16:34
 * @since jdk11
 */
public class UserDaoImpl extends DBUtil implements UserDao {
    Connection conn = getConnection();
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    public boolean userRegister(String username, String password) {
        boolean flag = false;

        //前端传来的参数账号密码插入到数据库
        String sql = "insert into t_user(username,password) values (?,?);";
        //发送sql结构
        try {
            preparedStatement = conn.prepareStatement(sql);
            //动态赋值
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            //发送sql 返回结果集
            int i = preparedStatement.executeUpdate();
            if (i>0){
                flag = true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return flag;
    }

    public User userLogin(String username, String password) {
        String sql = "select * from t_user where username = ? and password = ?";
        User user = null;
        try {
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                user = new User();
                user.setId(resultSet.getInt("userid"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user;
    }

    //查询用户名是否存在
    public boolean checkUsername(String username) {
        boolean flag = false;
        String sql = "select username from t_user where username = ?;";
        try {
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setObject(1,username);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                flag = true;
            }
            return flag;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
